package com.danciyixue.boot.dcyx.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.danciyixue.boot.core.security.util.SecurityUtils;
import com.danciyixue.boot.dcyx.model.query.ProgramsQuery;
import com.danciyixue.boot.dcyx.model.vo.CurrentProgramVO;
import com.danciyixue.boot.dcyx.model.vo.ProgramsVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.danciyixue.boot.dcyx.mapper.UserCurrentProgramMapper;
import com.danciyixue.boot.dcyx.service.UserCurrentProgramService;
import com.danciyixue.boot.dcyx.model.entity.UserCurrentProgram;
import com.danciyixue.boot.dcyx.model.form.UserCurrentProgramForm;
import com.danciyixue.boot.dcyx.model.query.UserCurrentProgramQuery;
import com.danciyixue.boot.dcyx.model.vo.UserCurrentProgramVO;
import com.danciyixue.boot.dcyx.converter.UserCurrentProgramConverter;
import com.danciyixue.boot.dcyx.service.ProgramsService;
import com.danciyixue.boot.dcyx.model.entity.Programs;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 用户当前选择教材项信息服务实现类
 *
 * @author youlaitech
 * @since 2025-06-22 07:38
 */
@Service
@DS("dcyx")
@RequiredArgsConstructor
public class UserCurrentProgramServiceImpl extends ServiceImpl<UserCurrentProgramMapper, UserCurrentProgram> implements UserCurrentProgramService {

    private final UserCurrentProgramConverter userCurrentProgramConverter;
//    private final ProgramsService programsService;
    /**
    * 获取用户当前选择教材项信息分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<UserCurrentProgramVO>} 用户当前选择教材项信息分页列表
    */
    @Override
    public IPage<UserCurrentProgramVO> getUserCurrentProgramPage(UserCurrentProgramQuery queryParams) {
        Page<UserCurrentProgramVO> pageVO = this.baseMapper.getUserCurrentProgramPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取用户当前选择教材项信息表单数据
     *
     * @param id 用户当前选择教材项信息ID
     * @return 用户当前选择教材项信息表单数据
     */
    @Override
    public UserCurrentProgramForm getUserCurrentProgramFormData(Long id) {
        UserCurrentProgram entity = this.getById(id);
        return userCurrentProgramConverter.toForm(entity);
    }
    
    /**
     * 新增用户当前选择教材项信息
     *
     * @param formData 用户当前选择教材项信息表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveUserCurrentProgram(UserCurrentProgramForm formData) {
        UserCurrentProgram entity = userCurrentProgramConverter.toEntity(formData);
        return this.save(entity);
    }
    
    /**
     * 更新用户当前选择教材项信息
     *
     * @param id   用户当前选择教材项信息ID
     * @param formData 用户当前选择教材项信息表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateUserCurrentProgram(Long id,UserCurrentProgramForm formData) {
        UserCurrentProgram entity = userCurrentProgramConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除用户当前选择教材项信息
     *
     * @param ids 用户当前选择教材项信息ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteUserCurrentPrograms(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的用户当前选择教材项信息数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    /**
     * 根据用户ID获取当前选中教材项
     *
     * @param userId 用户ID
     * @return 用户当前选中教材项信息
     */
    @Override
    public UserCurrentProgramVO getCurrentProgramByUserId(Long userId) {
        // 根据用户ID查询最新的当前教材项记录
        LambdaQueryWrapper<UserCurrentProgram> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserCurrentProgram::getUserId, userId)
                .orderByDesc(UserCurrentProgram::getUpdateTime)
                .last("LIMIT 1");

        UserCurrentProgram entity = this.getOne(queryWrapper);

        if (entity == null) {
            return null;
        }

        // 将实体转换为VO对象
        UserCurrentProgramVO vo = userCurrentProgramConverter.toVO(entity);

        // 补全教材名称等信息
//        if (vo != null && vo.getProgramId() != null) {
//            Programs program = programsService.getById(vo.getProgramId());
//            if (program != null) {
//                vo.setProgramName(program.getName());
//            }
//        }

        return vo;
    }

    /**
     * 更新用户当前选中教材项
     *
     * @param form 用户当前教材项表单数据
     * @return 是否更新成功
     */
    @Override
    public boolean updateCurrentProgram(UserCurrentProgramForm form) {
        // 检查用户是否已有当前教材项记录
        LambdaQueryWrapper<UserCurrentProgram> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserCurrentProgram::getUserId, form.getUserId())
                .orderByDesc(UserCurrentProgram::getUpdateTime)
                .last("LIMIT 1");

        UserCurrentProgram existingEntity = this.getOne(queryWrapper);

        if (existingEntity != null) {
            // 更新现有记录
            UserCurrentProgram entity = userCurrentProgramConverter.toEntity(form);
            entity.setId(existingEntity.getId());
            return this.updateById(entity);
        } else {
            // 创建新记录
            UserCurrentProgram entity = userCurrentProgramConverter.toEntity(form);
            return this.save(entity);
        }
    }



    /**
     * 根据当前用户Token获取当前教材详细信息
     *
     * @return 当前教材详细信息，包含系列、学期、学习进度等信息
     */
    @Override
    public CurrentProgramVO getCurrentProgramDetailByUserToken() {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        if (userId == null) {
            return null;
        }

        // 通过Mapper查询当前用户的教材详细信息
        CurrentProgramVO result = this.baseMapper.getCurrentProgramDetailByUserId(userId);

        return result;
    }
}
